import 'package:dio/dio.dart';
import 'package:common_utils/common_utils.dart' show LogUtil;
import 'package:flutter/services.dart';
import 'package:sp_util/sp_util.dart';
import 'package:testlzhu/data/common_net.dart';
import 'package:testlzhu/data/dev_server_config.dart';
import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:testlzhu/data/net/base_entity.dart';

class MyInterceptor implements InterceptorsWrapper {
  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    int errCode = err.response!.statusCode!;
    String? errMsg = err.response!.statusMessage;
    LogUtil.e("onError$errCode,$errMsg");
    handler.next(err);
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    getUid(options, handler);
  }

  @override
  void onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) {
    BaseEntity entity = BaseEntity.fromJson2(response.data);
    if(entity.code==2){
      SpUtil.clear();
    }
    handler.next(response);
  }

  getUid(RequestOptions options, RequestInterceptorHandler handler) async {
    const myPlugin = MethodChannel('com.example.jump/plugin');
    var invokeMethod = await myPlugin.invokeMethod("getUid");
    var hearData = CommonNet.getHearData();
    hearData['nonce'] = invokeMethod;
    var datamap = {};
    var queryParameters = options.queryParameters;
    if (queryParameters.isNotEmpty) {
      datamap.addAll(queryParameters);
    }
    datamap.addAll(hearData);
    if(options.data!=null){
      datamap.addAll(options.data);
    }
    var sortMap = sortMapMD5(datamap);
    hearData["sign"] = sortMap;
    options.headers = hearData;
    LogUtil.e("url=${options.uri}\n${options.headers}\n${options.data}");
    handler.next(options);
  }

  String sortMapMD5(Map datamap) {
    //排序
    var list = datamap.keys.toList();
    list.sort((a, b) {
      List<int> al = a.codeUnits;
      List<int> bl = b.codeUnits;
      for (int i = 0; i < al.length; i++) {
        if (bl.length <= i) return 1;
        if (al[i] > bl[i]) {
          return 1;
        } else if (al[i] < bl[i]) {
          return -1;
        }
      }
      return 0;
    });

    var treemap = {};

    var aas = "";
    for (var element in list) {
      treemap[element] = datamap[element];
      aas += element + "=" + datamap[element] + "&";
    }

    aas += "key=" + DevServerConfig.API_SIGN_KEY;
    var md5 = getMessageDigest(aas);

    return md5;
  }

  String getMessageDigest(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }
}
